package com.scs.application.modules.base.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.modules.base.entity.Location;
import com.scs.application.modules.base.entity.Matr;
import com.scs.application.modules.base.entity.SafeStock;
import com.scs.application.modules.base.mapper.LocationMapper;
import com.scs.application.modules.base.mapper.MatrMapper;
import com.scs.application.modules.base.mapper.SafeStockMapper;
import com.scs.application.modules.base.service.SafeStockService;
import com.scs.application.core.service.BaseServiceImpl;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 安全库存 服务实现类
 * </p>
 */
@Service
public class SafeStockServiceImpl extends BaseServiceImpl<SafeStockMapper, SafeStock> implements SafeStockService {

    @Autowired
    private MatrMapper matrMapper;

    @Autowired
    private LocationMapper locationMapper;

    @Override
    public void settingSafeLocation(String locationId, List<String> matrIdList) {

        Location location = locationMapper.selectById(locationId);
        if (location == null) {
            throw new BusinessException("库位不存在");
        }

        List<SafeStock> safeStocks = list(Wrappers.<SafeStock>query().select("matr_id").eq("location_id", locationId));

        Map<String, String> safeStockMap = safeStocks.stream().collect(Collectors.toMap(o -> o.getMatrId(), o -> o.getMatrId()));

        List<String> toAddMatrIdList = Lists.newArrayList();

        for (String matrId : matrIdList) {
            if (safeStockMap.get(matrId) == null) {
                toAddMatrIdList.add(matrId);
            }
        }
        if (toAddMatrIdList.isEmpty()) {
            return;
        }

        List<Matr> matrs = matrMapper.selectBatchIds(toAddMatrIdList);
        List<SafeStock> toAddSafeStocks = Lists.newArrayListWithExpectedSize(matrs.size());
        for (Matr matr : matrs) {
            SafeStock safeStock = new SafeStock();
            safeStock.setLocationId(locationId).setLocationName(location.getName()).setMatrModel(matr.getModel())
                    .setMatrId(matr.getId()).setMatrName(matr.getName()).setMatrSpec(matr.getSpec())
                    .setMinSkuQty(0.0).setMaxSkuQty(0.0).setReplenishToSkuQty(0.0);
            toAddSafeStocks.add(safeStock);
        }
        if (!toAddSafeStocks.isEmpty()) {
            this.saveBatch(toAddSafeStocks);
        }
    }


}
